const n = getApp().globalData.appUrl;
const not_token_router = ['pages/logins/logins', 'pages/register/register'];

module.exports = {
  request: function (url, data, method = 'POST', type = 'json') {
    const token = wx.getStorageSync('token'),
      page = getCurrentPages(),
      route = page[page.length - 1].route;
    console.log('接口:', url, data, method);
    if (!token && !not_token_router.includes(route)) {
      setTimeout(function () {
        wx.reLaunch({
          url: '/pages/logins/logins',
        });
      }, 100);
    }
    return new Promise(function (e, l) {
      wx.request({
        url: n + url,
        data: data || {},
        method: method,
        header: {
          'content-type':
            type === 'json' ? 'application/json' : 'application/x-www-form-urlencoded',
          Authorization: 'Bearer ' + (token || ''),
        },
        success: function (n) {
          console.log(url + '返回', n.data);
          if (n?.data?.code !== 200) {
            wx.showToast({
              title: n.data.msg,
              icon: 'none',
              duration: 2000,
            });
            if (n?.data?.code === 401) {
              wx.reLaunch({
                url: '/pages/logins/logins',
              });
              return;
            }
            return l(n.data);
          }
          e(n.data);
        },
        fail: function (e) {
          console.log('返回失败');
          wx.showToast({
            title: e.msg,
            icon: 'none',
            duration: 2000,
          });
          l(e);
        },
      }).onHeadersReceived(function (e) {});
    });
  },
  upLoadFile: function (url, filePath, formData = {}) {
    console.log('上传文件' + n + url);
    return new Promise(function (resolve, reject) {
      wx.uploadFile({
        url: n + url,
        filePath,
        name: 'file',
        header: {
          Authorization: wx.getStorageSync('token') || null,
        },
        formData: formData,
        success: function (e) {
          try {
            const data = JSON.parse(e.data);
            if (data.code !== 200) {
              wx.showToast({ title: '上传失败', icon: 'none' });
              reject(data);
              return;
            }
            resolve(data);
          } catch (error) {
            wx.showToast({ title: '上传失败', icon: 'none' });
            reject(error);
          }
        },
        fail: function (e) {
          reject(e);
        },
      });
    });
  },
};
